import { View, Navigator, Text, Button, Input, Image } from '@tarojs/components'
import { useState } from 'react'
import { AtButton, AtModal, AtModalContent, AtModalHeader, AtModalAction } from 'taro-ui'
import XImage from '../../components/XImage'
import Taro, { getCurrentInstance, useDidShow, useReady } from '@tarojs/taro'
import { AtBadge } from 'taro-ui'

import './index.scss'
import GlobalData from '../../global'
import XAuthNavigator from '../../components/XAuthNavigator'
import { showModal } from '../../utils'
//import { queryCurrentChargingOrderCountApi } from '../../services/ChargeLog'


export default () => {
  let [INIT, setINIT] = useState(false)
  let [userInfo, setuserInfo] = useState({avatar : '', nickName : ''}) //用户信息
  let [chargingCount, setchargingCount] = useState(0) //充电中数量
  let [deviceNo, setdeviceNo] = useState('') //设备号
  let [isOpenInputDeviceNo, setIsOpenInputDeviceNo] = useState(false) //是否打开填写设备号弹窗
  
  
  function inputDeviceNo(deNo) {
    setdeviceNo(deNo)
  }


  function updateUserInfo() {
    if(GlobalData.userInfo.avatar) {
      userInfo.avatar = GlobalData.userInfo.avatar
    }
    if(GlobalData.userInfo.nickName) {
      userInfo.nickName = GlobalData.userInfo.nickName
    }

    setuserInfo({...userInfo})
  }


  function confirmInputDeviceNo() {
    if(deviceNo !== '') {
      navToCharge(deviceNo)
      setIsOpenInputDeviceNo(false)
    }
  }

  function scanQr() { //扫码
    Taro.scanCode({
      success: (res) => {
        let deviceId = res.result
        if(deviceId.indexOf('http') == 0) {
          const url = new URL(deviceId)
          deviceId = url.searchParams.get('deviceNo') || ''
        }

        if(deviceId == '') {
          showModal('设备号不合法')
          return
        }
        navToCharge(deviceId)
      }
    })
  }

  function navToCharge(no) {
    const url = '/pages/charge/index?deviceId=' + no

    if(!GlobalData.isLogin) {
      Taro.navigateTo({
        url : '/pages/auth/getUserInfo/index?redirect=' + encodeURIComponent(url)
      })
    }else {
      Taro.navigateTo({
        url,
        success() {
          setIsOpenInputDeviceNo(false)
        }
      })
    }

    
  }

  

  async function waitLogin() {
    if(!GlobalData.isLogin) {
      setTimeout(() => {
        //console.log('等待登录')
        waitLogin()
      }, 1000)

      return
    }

    if(GlobalData.userInfo.avatar == '') { //去授权
      Taro.navigateTo({url : '/pages/auth/getUserInfo/index'})
    }else {
      updateUserInfo()
    }

    

    const $instance = getCurrentInstance()
    let q = $instance.router?.params.q
    if(q) { //从二维码跳进来
      q = decodeURIComponent(q)
    }

    // let count = await queryCurrentChargingOrderCountApi()
    // console.log(count)
    // setchargingCount(count)
    // GlobalData.chargingCount = count

  }


  useDidShow(() => {
    if(INIT) { //非第一次进来
      updateUserInfo() //更新用户信息
      setchargingCount(GlobalData.chargingCount) //更新用户正常充电的数量
    }
  })

  useReady(() => {
    setINIT(true)
    waitLogin()
  })

  

  const Ggreetings = () => {
    const date = new Date()
    const hour = date.getHours()
    if(hour >= 19 || hour <= 3) {
      return ('晚上好')
    }else if(hour < 10) {
      return('早上好')
    }else if(hour < 12) {
      return('中午好')
    }else {
      return('下午好')
    }

  }

  return <>
    <View className='page-header p-l-r'>
      <View className='flex-align-items-center'>
        <View className='flex-align-items-center flex-1'>
          {userInfo.avatar ? <Image className='user-avatar' mode='widthFix' src={userInfo.avatar} /> : <XImage className='user-avatar' src='default-avatar.png' /> }
          <View className='greetings-text'>
            {userInfo.nickName &&
              userInfo.nickName + '，'
            }
            {Ggreetings()}
          </View>
        </View>
        <Navigator hoverClass='none' url='/userClient/pages/map/index' className='near-site'>
          <XImage className='location-icon' src='small-location.png'></XImage>
          <Text>附近充电桩</Text>
        </Navigator>
      </View>
    </View>
    <View className='p-l-r m-t-40'>
      <View className='module'>
        <XAuthNavigator className='item text-center' url='/userClient/pages/charging/index'>
          <AtBadge value={chargingCount} maxValue={99}>
            <XImage className='icon' src='charging.png'></XImage>
          </AtBadge>
          <View className='title'>充电中</View>
        </XAuthNavigator>
        <XAuthNavigator className='item' url='/userClient/pages/chargeLog/index'>
          <XImage className='icon' src='record.png'></XImage>
          <View className='title'>充电记录</View>
        </XAuthNavigator>
        <XAuthNavigator className='item' url='/userClient/pages/wallet/index'>
          <XImage className='icon' src='wallet.png'></XImage>
          <View className='title'>钱包</View>
        </XAuthNavigator>
        <XAuthNavigator className='item' url='/userClient/pages/iccard/index'>
          <XImage className='icon' src='card.png'></XImage>
          <View className='title'>线上卡</View>
        </XAuthNavigator>
        {/* <Navigator className='item' url=''>
          <XImage className='icon' src='coupon.png'></XImage>
          <View className='title'>优惠券</View>
        </Navigator>
        <Navigator className='item' url=''>
          <XImage className='icon' src='customer-service.png'></XImage>
          <View className='title'>客服</View>
        </Navigator> */}
      </View>
    </View>

    <View className='p-l-r' style='margin-top:120rpx'>
      <AtButton type='primary' circle onClick={scanQr}>
        <View className='flex-align-items-center'>
          <XImage className='scan-icon' src='scan.png'></XImage><Text className='m-l-10'>扫码充电</Text>
        </View>
      </AtButton>
      <View className='text-center m-t-20' style='text-decoration: underline;' onClick={() => { setIsOpenInputDeviceNo(true); }}>输入设备号</View>
    </View>

    <AtModal isOpened={isOpenInputDeviceNo}>
        <AtModalHeader>输入设备号</AtModalHeader>
        <AtModalContent style='min-height:0'>
          <Input focus={isOpenInputDeviceNo} type='text' confirm-type='done' className='input-deviceno' onInput={e => inputDeviceNo(e.target.value)}  />
        </AtModalContent>
        <AtModalAction> <Button onClick={() => { setIsOpenInputDeviceNo(false); }}>取消</Button> <Button onClick={confirmInputDeviceNo}>确定</Button> </AtModalAction>
    </AtModal>
    
  </>
}